<template>
  <div class="club-management">
    <h2>社团管理</h2>
    
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="queryParams" @submit.prevent>
        <el-form-item label="社团名称">
          <el-input v-model="queryParams.name" placeholder="请输入社团名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="queryParams.leaderName" placeholder="请输入负责人姓名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 操作按钮 -->
    <div class="operation-container">
      <el-button type="primary" @click="handleAdd" v-if="isAdmin">添加社团</el-button>
    </div>
    
    <!-- 社团表格 -->
    <el-table v-loading="loading" :data="clubList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="60"></el-table-column>
      <el-table-column prop="name" label="社团名称" width="180"></el-table-column>
      <el-table-column prop="description" label="社团描述" show-overflow-tooltip></el-table-column>
      <el-table-column label="负责人" width="150">
        <template #default="scope">
          {{ scope.row.leader ? (scope.row.leader.realName || scope.row.leader.username) : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <el-button 
            v-if="isAdmin || (isClubLeader && scope.row.leaderId === userInfo.id)"
            link 
            type="primary" 
            @click="handleEdit(scope.row)">编辑</el-button>
          <!-- <el-button 
            link 
            type="danger" 
            @click="handleDelete(scope.row)" 
            v-if="isAdmin || (isClubLeader && scope.row.leaderId === userInfo.id)">删除</el-button> -->
            <el-button 
            link 
            type="danger" 
            @click="handleDelete(scope.row)" 
            v-if="isAdmin ">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getClubList, deleteClub } from '@/api/club'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const clubList = ref([])
const total = ref(0)

// 用户信息
const userInfo = computed(() => userStore.userInfo)
const isAdmin = computed(() => userInfo.value.role === 'admin')
const isClubLeader = computed(() => userInfo.value.role === 'club_leader')

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  leaderName: ''
})

// 获取社团列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getClubList(queryParams)
    if (res.data && res.code === 200) {
      clubList.value = res.data.list
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取社团列表失败')
    }
  } catch (error) {
    console.error('获取社团列表出错:', error)
    ElMessage.error('获取社团列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置
const handleReset = () => {
  queryParams.name = ''
  queryParams.leaderName = ''
  queryParams.page = 1
  getList()
}

// 添加社团
const handleAdd = () => {
  router.push('/clubs/add')
}

// 编辑社团
const handleEdit = (row) => {
  router.push(`/clubs/edit/${row.id}`)
}

// 删除社团
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除社团 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteClub(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除社团出错:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getList()
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.club-management {
  padding: 20px;
}

.search-form {
  background-color: #f5f7fa;
  padding: 18px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 